package com.traffic.handler;

import cn.hutool.core.util.ObjectUtil;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.exception.BaseException;
import com.traffic.util.JwtUtil;
import com.traffic.util.PowerUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/26
 */
@Aspect
@Component
@Slf4j
public class AopAuthHandler {
    @Autowired
    private PowerUtil powerUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @Pointcut("@annotation(com.traffic.annotation.Power)")
    public void check() {}

    @Pointcut("@annotation(com.traffic.annotation.NeedLogin)")
    public void needLogin() {}

    @Around("check()")
    public Object aroundCheck(ProceedingJoinPoint joinPoint) {
        log.info("AOP---START");
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        powerUtil.authCheck(method);
        log.info("AOP--END");
        try {
            Object result = joinPoint.proceed();
            return result;
        } catch (Throwable throwable) {
            throw new BaseException(Status.UNKNOWN_ERROR);
        }
    }

    @Around("needLogin()")
    public Object aroundLogin(ProceedingJoinPoint joinPoint) {
        log.info("AOP---START");
        if (!jwtUtil.check(jwtUtil.getAccount(Const.TAG_USER))) {
            throw new BaseException(Status.NOT_ERROR);
        }
        log.info("AOP--END");
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throw new BaseException(Status.UNKNOWN_ERROR);
        }
    }
}
